#!/usr/local/bin/ruby
# Copyright (C) 2003-2010 Wang Pengcheng <wpc0000@gmail.com>
# , released under the MIT license
# You may obtain a template of the MIT License at
# http://www.opensource.org/licenses/mit-license.php
$KCODE = 'utf8'

BASIC_SIZE = 1500

require 'erb'
require 'es2utils'

delay_map = {}

pathes_list = ['1->3->31', '1->3->4->41', '2->4->41', '1->2->4->41', '3->2->21', '3->4->41']
PATH_MAP = {'1'=>'R1', '2'=>'R2' ,'3'=>'R3', '4'=>'R4','11'=>'Net1', '21'=>'Net2', '31'=>'Net3', '41' => 'Net4'}

pathes_list.each do |path|
  delay_map[path] = []
end

queue_map = {}
queue_list = ['1-2', '1-3', '3-2', '4-41', '2-4', '3-4', '3-31', '2-21', '41', '31', '21']
DROP_VALUE = 'drop'
QUEUE_MAP = {'1-2'=>'1A', '1-3'=>'1B', '3-2'=>'3A', '4-41'=>'4A', '2-4'=>'2B', '3-4'=>'3B', '3-31'=>'3C', '2-21'=>'2A', '41'=>DROP_VALUE, '31'=>DROP_VALUE, '21'=>DROP_VALUE}

queue_list.each do |queue|
  queue_map[queue] = []
end

data = File.read('ES2K5.txt').split("\n")
data.each do |line|
  if /(.+):\s*(.+)\(Length:(\d+)\)CIP\((\d+)\/.+\).+/=~line
    pdata =Regexp.last_match
    delay_map[pdata[1]]<<{:mean=>pdata[2].to_f, :length=>pdata[3].to_i, :batches_size=>pdata[4].to_i}
  elsif /(.+): All=(\d+).+Loss Rate=(.+) CIP\((\d+)/=~line
    pdata =Regexp.last_match
    queue_map[pdata[1]]<<{:all=>pdata[2].to_i, :mean=>pdata[3].to_f, :batches_size=>pdata[4].to_i}
  end
end

delay_results = {}

def to_path(key)
  pathes = key.split(Pachet::PATH_SPIL)
  new_pathes = []
  new_pathes<<PATH_MAP[pathes[0]+'1']
  pathes.each do |path|
    new_pathes << PATH_MAP[path]
  end
  new_pathes.join("\\to{}")
end

def to_queue(key)
  QUEUE_MAP[key]
end

delay_map.each_pair do |key,value|
  datas = []
  length = 0
  value.each do |v|
    datas<<v[:mean]
    length += v[:length]
  end
  cip = Array.cip(datas)
  delay_results[key] = {
    :label => to_path(key),
    :per => cip[:per],
    :mean => cip[:mean],
    :length => length/BASIC_SIZE,
    :batch => BASIC_SIZE
  }
end

queue_results = {}
queue_map.each_pair do |key,value|
  next if(to_queue(key)==DROP_VALUE)
  datas = []
  all = 0
  value.each do |v|
    datas<<v[:mean]
    all += v[:all]
  end
  cip = Array.cip(datas)
  queue_results[key] = {
    :label => to_queue(key),
    :per => cip[:per],
    :mean => cip[:mean],
    :length => all/BASIC_SIZE,
    :batch => BASIC_SIZE
  }
end

def networkValues(values)
  res = []
  values.each_pair do |k, value|
    r = ''
    r << '$'<<value[:label].to_s<<'$' << '&' << value[:mean].to_s << '&' << value[:per].to_s << '&'<< value[:length].to_s << '&' << value[:batch].to_s
    res << r
  end
  res.sort!
  res.join("\\\\\n")
end

nwValues = delay_results
nwLossRate = queue_results

template = ERB.new(File.read('templateS2.tex'))
File.open('102s.tex','w')do |nf|
  nf.puts template.result(binding)
end

